package com.easy.tool.utils.file;

import com.easy.tool.anno.BeanDes;
import com.easy.tool.anno.MethodDes;
import com.easy.tool.utils.array.ArrayUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 高俊
 * @create 2021-09-2021/9/3-10:28
 */
@BeanDes(name = "文件工具类", des = "实现创建，删除，写入，读取等操作")
public class FileUtils {

    private static Logger logger = Logger.getLogger(FileUtils.class);

    /**
     * 创建文件夹
     * @param path
     * @return 1:已存在；2:创建成功；0：创建失败
     */
    @MethodDes(des = "创建文件夹",explain = "1:已存在；2:创建成功；0：创建失败",param = {"arg0-> path：指定路径"})
    public static int createFloder(String path){
        File file = new File(path);
        if (!file.exists()){
            boolean bool = file.mkdirs();
            if (bool){
                return 2;
            }
            return 0;
        }
        return 1;
    }

    /**
     * 创建文件
     * @param path
     * @return
     */
    @MethodDes(des = "创建文件",param = {"arg0-> path：指定路径"})
    public static boolean createNewFile(String path){
        boolean bool = false;
        File file = new File(path);
        if (!file.exists()){
            try {
                bool = file.createNewFile();
            } catch (Exception e) {
                logger.error("创建文件失败！！");
            }
        }else {
            logger.warn("该文件已存在");
            bool = true;
        }
        return bool;
    }

    /**
     * 写入文件数据
     * @param path 文件路径
     * @param data 数据
     */
    @MethodDes(des = "写入文件数据",param = {"arg0-> path：指定文件路径","arg1-> data：写入的数据"})
    public static void writerFile(String path,String data){
        boolean bool = new File(path).exists();
        if (bool){
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(path));
                writer.write(data);
                writer.close();
            }catch (Exception e){
                logger.error("文件写入失败");
            }

        }
    }

    /**
     * 追加文件数据
     * @param path 文件路径
     * @param data 追加数据
     */
    @MethodDes(des = "追加文件数据",param = {"arg0-> path：指定路径","arg1-> data：追加数据"})
    public static void appendFile(String path,String data){
        boolean bool = new File(path).exists();
        if (bool){
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(path,true));
                writer.write("\n" + data);
                writer.close();
            }catch (Exception e){
                logger.error("文件写入失败");
            }

        }
    }

    /**
     * 读取文件内容
     * @param path 文件路径
     */
    @MethodDes(des = "读取文件内容",param = {"arg0-> path：指定路径"})
    public static  void readerFile(String path){
        boolean bool = new File(path).exists();
        if (bool){
            try {
                BufferedReader reader = new BufferedReader(new FileReader(path));
                String data;
                while ((data = reader.readLine()) != null){
                    System.out.println(data);
                }
                reader.close();
            }catch (Exception e){
                logger.error("文件写入失败");
            }
        }
    }


    /**
     * 文件删除
     * @param file
     */
    @MethodDes(des = "文件删除",param = {"arg0-> file：需要删除的文件File类型"})
    public static void deleteFile(File file){
        File[] files = file.listFiles();
        if (files != null && files.length > 0){
            for (File f : files) {
                File[] f1 = f.listFiles();
                if (f1 == null || f1.length == 0){
                    f.delete();
                }
                deleteFile(f);
            }
            deleteFile(file);
        }else {
            file.delete();
        }
    }


    /**
     * 获取文件树
     * @throws IOException
     */
    @MethodDes(des = "获取文件树",explain = "会对指定路径下的文件夹和文件进行遍历",param = {"arg0-> path：指定路径"})
    private static Map<String, List<String>> getFilsTree(String path) throws IOException {
        AtomicInteger dirCount = new AtomicInteger();
        AtomicInteger fileCount = new AtomicInteger();

        Map<String, List<String>> map = new HashMap<>();
        final String [] curr = {};

        Files.walkFileTree(Paths.get(path),new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                logger.debug("======> Direction：" + dir);
                curr[0] = dir.toString();
                dirCount.incrementAndGet();
                return super.preVisitDirectory(dir, attrs);
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                logger.debug(file);

                List<String> list = map.get(curr[0]);
                list = ArrayUtils.CollectionEmpty(list);
                list.add(file.toString());
                map.put(curr[0],list);

                fileCount.incrementAndGet();
                return super.visitFile(file, attrs);
            }
        });
        logger.debug("dirCount：" + dirCount);
        logger.debug("fileCount：" + fileCount);
        return map;
    }
}
